package com.example.accessingdatajpa.service.impl;

import com.example.accessingdatajpa.pojo.Category;
import com.example.accessingdatajpa.repository.CategoryRepository;
import com.example.accessingdatajpa.response.RestResponse;
import com.example.accessingdatajpa.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service("categoryService")
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    //find all categories
    @Override
    @Transactional
    public RestResponse<List<Category>> queryAllCategory(){
        RestResponse<List<Category>> response = new RestResponse<>();
        try {
            List<Category> data = categoryRepository.findAll();
            response.setStatus(200);
            response.setMessage("查询成功");
            response.setData(data);
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    //add new category
    @Override
    @Transactional
    public RestResponse<String> addOneCategory(Category category){
        RestResponse<String> response = new RestResponse<>();
        try {
            categoryRepository.save(category);
            response.setStatus(200);
            response.setMessage("ok");
            response.setData("保存成功");
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
        }
        return response;
    }
}
